/**
 * 系统后台元数据表配置JS-systemDataConfig.jsp
 */

//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";

$(document).ready(function () {
    var ismark = GetQueryString("ismark");
    var dbkey = GetQueryString("dbkey");
    var dtConfigId = GetQueryString("dtConfigId");
    if (ismark == "1") {
        //新增表
        if (!testDataconn(dbkey)) {
            bootbox.alert(dbkey);

            showMsg("1数据源连接失败,请检测数据源连接!","error");
            //bootbox.alert("1数据源连接失败,请检测数据源连接!");
            return;
        }
        $("#hid_IsMark").val(ismark);
        $("#dtConn").val(dbkey);
        $("#hid_dbkey").val(dbkey);
        bingDataTable(dbkey);
    } else if (ismark == "2") {
        //修改表
        var cfgtable = "";
        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataConfig/getCfgTable',
            data: {dtConfigId: dtConfigId},
            async: false,
            success: function (res) {
                cfgtable = res;
            }
        });
        if (!testDataconn(cfgtable.dtConn)) {
            //bootbox.alert("2数据源连接失败,请检测数据源连接!")
            showMsg("2数据源连接失败,请检测数据源连接!","error");
            return;
        }
        bingDataTable(cfgtable.dtConn);
        $("#dtName").val(cfgtable.dtName).trigger("change");
        $("#dtConfigId").val(cfgtable.dtConfigId);
        $("#dtNameCn").val(cfgtable.dtNameCn);
        $("#dtOrder").val(cfgtable.dtOrder);
        $("#dtConn").val(cfgtable.dtConn);
        $("#dtPrimarykey").val(cfgtable.dtPrimarykey);
        $("#dtRemark").val(cfgtable.dtRemark);
        $("#hid_dtguid").val(cfgtable.guid);
        $("#hid_dtConfigId").val(cfgtable.dtConfigId);
        $("#dtName").attr("disabled", "disabled");
        $("#dtConfigId").attr("disabled", "disabled");
        $("#hid_dbkey").val(cfgtable.dtConn);
        $("#hid_IsMark").val(ismark);
    }

    //测试数据源连接
    function testDataconn(dbKey) {
        var result = false;
        $.ajax({
            url: postPath + "/system/dataConfig/testDataConnection",
            type: "POST",
            data: {dbKey: dbKey},
            async: false,
            success: function (res) {
                result = res;
            }
        });
        return result;
    }

    /*****************************Begin表信息配置*********************/
    //表信息配置-绑定数据表列表
    function bingDataTable(dtconn) {
        var strTabletxt = "";
        $("#dtName").empty();
        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataConfig/tableList',
            data: {dbkey: dtconn},
            async: false,
            success: function (data) {
                $("#dtName").append("<option value=''>请选择表</option>");
                $.each(data, function (i, e) {
                    var strtxt = "<option value=" + e.TABLE_NAME + ">" + e.TABLE_NAME;
                    if (e.COMMENTS != null && e.COMMENTS != "" && e.COMMENTS != "undefined") {
                        strtxt += "(" + e.COMMENTS + ")";
                    }
                    strtxt += "</option>";
                    strTabletxt += strtxt;
                });
                $("#dtName").append(strTabletxt);
            }

        });
        $("#dtName").val("").trigger("change");
    }

    //数据源表-设置筛选功能
    $("#dtName").select2();

    //表信息配置-选择数据表
    $("#dtName").click(function () {
        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataConfig/parmaryKey',
            data: {dbkey: $("#dtConn").val(), dtname: $("#dtName").val()},
            success: function (data) {
                $("#dtOrder").val(data);
                $("#dtPrimarykey").val(data);
                $("#dtConfigId").val($("#hid_dbkey").val() + "_" + $("#dtName").val());
                var dtnametext = $("#dtName").find("option:selected").text();
                dtnametext = dtnametext.substring(dtnametext.indexOf("(") + 1, dtnametext.lastIndexOf(")"));
                $("#dtNameCn").val(dtnametext);
                $("#dtRemark").val(dtnametext);
            }
        });
    });

    //表信息配置-保存
    $("#btn_tableSave").click(function () {
        var validresult = validTableInfo();
        var saveUrl = "";
        if ($("#hid_IsMark").val() == "1") {
            saveUrl = postPath + '/system/dataConfig/add';
        } else {
            saveUrl = postPath + '/system/dataConfig/update';
        }

        if (validresult) {
            var pp = {
                dtName: $("#dtName").val(),
                dtConfigId: $("#dtConfigId").val(),
                dtNameCn: $("#dtNameCn").val(),
                dtOrder: $("#dtOrder").val(),
                dtConn: $("#dtConn").val(),
                dtPrimarykey: $("#dtPrimarykey").val(),
                dtRemark: $("#dtRemark").val(),
                guid: $("#hid_dtguid").val()
            }
            $.ajax({
                type: 'POST',
                url: saveUrl,
                async: false,
                data: JSON.stringify(pp),
                dataType: 'json',
                contentType: "application/json",
                success: function (res) {
                    if (res > 0) {
                        if ($("#hid_IsMark").val() == "1") {
                            $("#hid_IsMark").val(2);
                            $("#dtName").attr("disabled", "disabled");
                            $("#dtConfigId").attr("disabled", "disabled");
                            $.ajax({
                                type: 'POST',
                                url: postPath + '/system/dataConfig/getCfgTable',
                                data: {dtConfigId: $("#dtConfigId").val()},
                                async: false,
                                success: function (res) {
                                    $("#hid_dtguid").val(res.guid);
                                }
                            });
                        }

                        showMsg("保存成功!", "success");
                        $("#hid_dtConfigId").val($("#dtConfigId").val());
                    } else {
                        showMsg("保存失败,请刷新后重试!", "error");
                    }
                }
            });
        }

    });

    //表信息配置-验证
    function validTableInfo() {
        if ($("#dtName").val() == "") {
            $("#valide_dtMessage").html("数据表不能为空,请选择!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtConfigId").val() == "") {
            $("#valide_dtMessage").html("表标识不能为空,请输入!");
            return false;
        } else {
            if ($("#hid_IsMark").val() == "1") {
                var dtConfignum = 0;
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/dataConfig/getdtConfigId',
                    data: {dtConfigId: $("#dtConfigId").val()},
                    async: false,
                    dataType: 'json',
                    success: function (num) {
                        dtConfignum = num;
                    }
                });
                if (dtConfignum > 0) {
                    $("#valide_dtMessage").html("表标识已存在，请重新输入!");
                    return false;
                } else {
                    $("#valide_dtMessage").html("");
                }
            } else {
                $("#valide_dtMessage").html("");
            }
        }

        if ($("#dtNameCn").val() == "") {
            $("#valide_dtMessage").html("请输入表中文名称!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtOrder").val() == "") {
            $("#valide_dtMessage").html("请输入表排序字段!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtConn").val() == "") {
            $("#valide_dtMessage").html("请输入数据源标识!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }


        return true;
    }

    //表信息配置-清空信息
    function cleanTableInfo() {
        $("#dtName").select2("val", "");
        $("#dtConfigId").val("");
        $("#dtNameCn").val("");
        $("#dtOrder").val("");
        $("#dtConn").val("");
        $("#dtPrimarykey").val("");
        $("#dtRemark").val("");
        $("#hid_IsMark").val("");
        $("#hid_dtguid").val("");
        $("#hid_dtConfigId").val("");
        $("#dtName").removeAttr("disabled");
        $("#dtConfigId").removeAttr("disabled");
    }

    //定位到表信息配置选项卡
    function locationTab() {
        $('#myTab a[href="#tab_1_1_1"]').tab('show');
    }

    /*****************************End表信息配置*********************/

    /*****************************Begin字段配置*********************/
    //字段配置tab
    $("#a_tab_field").click(function () {
        var dtConfigId = $("#hid_dtConfigId").val();
        if (dtConfigId == "") {
            bootbox.alert("请先设置表信息!");
            setTimeout(locationTab, 200);
            return;
        }
        $("#tb_fieldList").bootstrapTable('refresh');
        getFieldList();
    });

    //字段配置-获取字段列表
    function getFieldList() {
        $("#tb_fieldList").bootstrapTable({
            url: postPath + '/system/dataConfig/getAllField',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            cache: false, // 是否使用缓存
            queryParams: queryFieldParams,
            uniqueId: "guid", // 每一行的唯一标识
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段名称',
                field: 'dfName',
                align: 'center',
                valign: 'middle'
            }, {
                title: '中文名称',
                field: 'dfNameCn',
                align: 'center',
                valign: 'middle',
            }, {
                title: '字段排序',
                field: 'dfOrder',
                align: 'center',
                valign: 'middle',
            }, {
                title: '字段类型',
                field: 'dtType',
                align: 'center',
                valign: 'middle'
            }, {
                title: '是否主键',
                field: 'dfIsprimarykey',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == 1) {
                        return "是";
                    } else {
                        return "否";
                    }
                }
            }, {
                title: '备注',
                field: 'remark',
                align: 'center',
                valign: 'middle',
            }],
        });
    }

    //字段配置-字段列表参数
    function queryFieldParams(pageReqeust) {
        var temp = {
            dtConfigId: $("#hid_dtConfigId").val()
        };
        return temp;
    }

    //字段配置-新增字段
    $("#btn_fieldAdd").click(function () {
        var frameSrc = postPath + "/FieldList/index?dtConfigId=" + $("#hid_dtConfigId").val() + "&operateMethod=add";
        $("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
    });

    //字段配置-修改字段
    $("#btn_fieldUpdate").click(function () {
        var rowList = $("#tb_fieldList").bootstrapTable("getSelections");
        var jsonDataList = encode_utf8(JSON.stringify(rowList));

        // here convert json object
        var frameSrc = postPath + "/FieldList/index?dtConfigId=" + $("#hid_dtConfigId").val() + "&operateMethod=update&jsonDataList=" + jsonDataList;
        $("#fieldIframe").attr("src", frameSrc);
        $("#FieldModul").modal('show');
    });



    //字段配置-新增字段Modul关闭监听事件
    $("#FieldModul").on('hidden.bs.modal', function (e) {
        $("#tb_fieldList").bootstrapTable('refresh');
    });

    //字段配置-删除字段
    $("#btn_fieldDel").click(function () {
        var row = $('#tb_fieldList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        }

        var guidList = "";
        $.each(row, function (i, e) {
            guidList += e.dfName + " " + e.dfNameCn + "<br/>";
        });

        var deleteFunction = function (result) {
            if (result == false)
                return;
            var guids = "";
            $.each(row, function (i, e) {
                guids += e.guid + ",";
            });
            guids = guids.substring(0, guids.length - 1);
            $.ajax({
                url: postPath + '/system/dataConfig/delField',
                type: 'POST',
                data: {guids: guids},
                success: function (data) {
                    $('#tb_fieldList').bootstrapTable('refresh');
                },
                error: function () {
                }

            });
        }

        confirmDelete(guidList, deleteFunction)
    });

    /*****************************End字段配置*********************/

    /*****************************Begin字段枚举配置*********************/
    //字段枚举配置tab
    $("#a_tab_fieldEnum").click(function () {
        var dtConfigId = $("#hid_dtConfigId").val();
        if (dtConfigId == "") {
            bootbox.alert("请先设置表信息!");
            setTimeout(locationTab, 200);
            return;
        }
        createEnumList();
    });

    //字段枚举配置
    function createEnumList() {
        $("#tb_enumList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/dataConfig/getBaseFieldenumList',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            cache: false, // 是否使用缓存
            queryParams: {dtConfigId: $("#hid_dtConfigId").val()},
            uniqueId: "guid", // 每一行的唯一标识
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '字段Code',
                field: 'fieldname',
                align: 'center',
                valign: 'middle'
            }, {
                title: '枚举Code',
                field: 'enumcode',
                align: 'center',
                valign: 'middle'
            }, {
                title: '枚举名称',
                field: 'enumname',
                align: 'center',
                valign: 'middle'
            }, {
                title: '枚举值',
                field: 'enumvalue',
                align: 'center',
                valign: 'middle'
            }]
        });

    }

    //添加枚举字段
    $("#btn_enumAdd").click(function () {
        validateEnum();
        getNotInEnumFieldList();
        $("#enumModul").modal('show');
    });

    //查询没有设置枚举的字段列表
    function getNotInEnumFieldList() {
        var strTabletxt = "";
        $("#fieldname").empty();
        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataConfig/getFieldNotInFieldenum',
            data: {dtConfigId: $("#hid_dtConfigId").val()},
            async: false,
            success: function (data) {
                $.each(data, function (i, e) {
                    var strtxt = "<option value=" + e.dfName + ">" + e.dfNameCn + "(" + e.dfName + ")</option>";
                    strTabletxt += strtxt;
                });
                $("#fieldname").append(strTabletxt);
            }

        });
        $("#fieldname").select2();
    }

    //字段枚举配置-维护枚举字段Modul关闭监听事件
    $("#enumModul").on('hidden.bs.modal', function (e) {
        $("#tb_enumList").bootstrapTable('refresh');
    });

    //修改枚举字段
    $("#btn_enumEdit").click(function () {
        validateEnum();
        getNotInEnumFieldList();
        var row = $('#tb_enumList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        }

        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataConfig/getFieldEnumByguid',
            data: {guid: row[0].guid},
            success: function (data) {
                $("#hid_enumguid").val(data.guid);
                $("#fieldname").val(data.fieldname).trigger("change");
                $("#enumcode").val(data.enumcode);
                $("#enumname").val(data.enumname);
                $("#enumvalue").val(data.enumvalue);
                $("#enumtype").val(data.enumtype);
            }
        });
        $("#enumModul").modal('show');
    });

    //删除枚举字段
    $("#btn_enumDel").click(function () {
        var row = $('#tb_enumList').bootstrapTable('getSelections');
        if (row == null || row == "") {
            bootbox.alert("请选择一行!");
            return;
        }

        var deleteFunction = function (result) {
            if (result == false)
                return;
            var guids = "";
            $.each(row, function (i, e) {
                guids += e.guid + ",";
            });
            guids = guids.substring(0, guids.length - 1);
            $.ajax({
                url: postPath + '/system/dataConfig/deleteBaseFieldenum',
                type: 'POST',
                data: {guids: guids},
                success: function (data) {
                    showMsg("删除成功!", "success");
                    $('#tb_enumList').bootstrapTable('refresh');
                },
                error: function () {
                    showMsg("删除失败!", "error");
                }
            });
        };

        var message = "";
        $.each(row, function (i, e) {
            console.log("i,e", i, e)
            message += e.enumcode + "," + e.enumvalue + "<br/>";
        });

        confirmDelete(message, deleteFunction);


    });

    //保存字段枚举
    $("#btn_enumSave").click(function () {
        if ($("#enumcode").val() == "") {
            $("#enumError").html("请输入枚举code!");
            return;
        } else {
            if (/^[A-Z]+$/.test($("#enumcode").val())) {
                $("#enumError").html("");
            } else {
                $("#enumError").html("只能输入大写字母!");
                return;
            }

        }

        if ($("#enumname").val() == "") {
            $("#enumError").html("请输入枚举名称!");
            return;
        } else {
            $("#enumError").html("");
        }

        if ($("#enumvalue").val() == "") {
            $("#enumError").html("请输入枚举值!");
            return;
        } else {
            $("#enumError").html("");
        }
        var editurl = "";
        if ($("#hid_enumguid").val() == "") {
            editurl = postPath + '/system/dataConfig/addBaseFieldenum';
        } else {
            editurl = postPath + '/system/dataConfig/updateBaseFieldenum';
        }
        var fieldenum = {
            "guid": $("#hid_enumguid").val(),
            "dtConfigId": $("#hid_dtConfigId").val(),
            "fieldname": $("#fieldname").val(),
            "enumname": $("#enumname").val(),
            "enumvalue": $("#enumvalue").val(),
            "enumcode": $("#enumcode").val(),
            "enumtype": $("#enumtype").val()
        };

        $.ajax({
            type: 'POST',
            url: editurl,
            async: false,
            data: JSON.stringify(fieldenum),
            dataType: 'json',
            contentType: "application/json",
            success: function (res) {
                if (res > 0) {
                    showMsg("保存成功!", "success");
                    $('#tb_enumList').bootstrapTable('refresh');
                    $("#enumModul").modal('hide');
                } else {
                    showMsg("保存失败,请刷新后重试!", "error");
                }
            }
        });
    });

    //清空验证
    function validateEnum() {
        $("#hid_enumguid").val("");
        $("#enumcode").val("");
        $("#enumname").val("");
        $("#enumvalue").val("");
        $("#enumtype").val("0");
    }

    /*****************************End字段枚举配置*********************/

    /*****************************Begin数据预览*********************/
    //数据预览tab
    $("#a_tab_view").click(function () {
        var dtConfigId = $("#hid_dtConfigId").val();
        if (dtConfigId == "") {
            bootbox.alert("请先设置表信息!");
            setTimeout(locationTab, 200);
            return;
        }
        $("#tb_viewList").bootstrapTable('refresh');
        dataView();
    });

    //数据预览-生成表格
    function dataView() {
        var columns = [];
        //数据预览-创建表格
        $.ajax({
            url: postPath + '/system/dataConfig/getAllViewField',
            type: 'POST',
            async: false,
            data: {dtConfigId: $("#hid_dtConfigId").val(), num: Math.random()},
            success: function (data) {
                $.each(data, function (i, e) {
                    var field = "";
                    var fieldCn = "";
                    field = e.dfName;
                    if (e.dfNameCn == null || e.dfNameCn == "" || e.dfNameCn == "null") {
                        fieldCn = e.dfName;
                    } else {
                        fieldCn = e.dfNameCn;
                    }
                    columns.push({"field": field, "title": fieldCn, "align": 'center', "valign": 'middle'});
                });
            },
            error: function () {
                showMsg("数据加载失败!","error");
            }
        });

        //数据预览-数据列表
        $("#tb_viewList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/dataConfig/viewData',
            undefinedText: '-',
            pagination: true, // 分页
            striped: true, // 是否显示行间隔色
            queryParams: queryViewParams,
            cache: false, // 是否使用缓存
            pageList: [5, 10, 20],
            toolbar: "",// 指定工具栏
            showColumns: false, // 显示隐藏列
            showRefresh: false, // 显示刷新按钮
            uniqueId: "dbKey", // 每一行的唯一标识
            sidePagination: "server", // 服务端处理分页
            columns: columns
        });
    }

    //数据预览-查询条件与分页数据
    function queryViewParams(pageReqeust) {
        var temp = {
            order: pageReqeust.order,
            pageNo: pageReqeust.offset / pageReqeust.limit + 1,
            pageSize: pageReqeust.limit,
            dtConfigId: $("#hid_dtConfigId").val()
        };
        return temp;
    }

    /*****************************End数据预览*********************/

});

//子页面调用父页面方法-关闭模态框
function closeModul() {
    $("#FieldModul").modal('hide');
}

//获取参数方法
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//返回操作
function goback() {
    window.location.href = postPath + "/systemDataConfigList/index";
}

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}

function encode_utf8(s) {
  return encodeURIComponent(s);
}


function confirmDelete(message, confirmFunction){
    var messageObj = {
        title: '确认删除？',
        message: message ,
        callback: confirmFunction
    }
    bootbox.confirm(messageObj);
}
